package net.xju3_4.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.Result;
import net.xju3_4.entity.UserEntity;
import net.xju3_4.service.UserProfileService;
import net.xju3_4.service.impl.UserProfileServiceImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户资料控制器
 * 独立的用户资料管理控制器
 */
@RequestMapping("/api/userProfile")
public class UserProfileController {

    private UserProfileService userProfileService = new UserProfileServiceImpl();

    /**
     * 获取用户资料
     */
    @RequestMapping("/get.do")
    public void getUserProfile(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            
            if (userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
                return;
            }
            
            UserEntity userProfile = userProfileService.getUserProfile(userId);
            
            if (userProfile != null) {
                JSONUtil.printByJSON(resp, Result.success(userProfile, "查询成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("用户不存在"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 更新用户资料
     */
    @RequestMapping("/update.do")
    public void updateUserProfile(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");

            String userId = req.getParameter("userId");
            String realName = req.getParameter("realName");
            String phone = req.getParameter("phone");
            String avatarUrl = req.getParameter("avatarUrl");
            String idCard = req.getParameter("idCard");
            String driverLicense = req.getParameter("driverLicense");

//            System.out.println("DEBUG: 接收到更新请求 - userId: " + userId);
//            System.out.println("DEBUG: realName: " + realName);
//            System.out.println("DEBUG: phone: " + phone);
            System.out.println("DEBUG: avatarUrl: " + avatarUrl);
//            System.out.println("DEBUG: idCard: " + idCard);
//            System.out.println("DEBUG: driverLicense: " + driverLicense);

            if (userId == null || userId.trim().isEmpty()) {
                JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
                return;
            }

            // 构建更新数据
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("userId", userId);
            updateData.put("realName", realName);
            updateData.put("phone", phone);
            updateData.put("avatarUrl", avatarUrl);
            updateData.put("idCard", idCard);
            updateData.put("driverLicense", driverLicense);

            boolean success = userProfileService.updateUserProfile(updateData);

            if (success) {
                JSONUtil.printByJSON(resp, Result.success("资料更新成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("资料更新失败"));
            }

        } catch (Exception e) {
            System.out.println("DEBUG: 控制器异常: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 修改密码
     */
    @RequestMapping("/changePassword.do")
    public void changePassword(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            String oldPassword = req.getParameter("oldPassword");
            String newPassword = req.getParameter("newPassword");
            
            if (userId == null || oldPassword == null || newPassword == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            // 密码强度验证
            if (!isValidPassword(newPassword)) {
                JSONUtil.printByJSON(resp, Result.fail("密码强度不够，请使用8-20位包含字母和数字的密码"));
                return;
            }
            
            boolean success = userProfileService.changePassword(userId, oldPassword, newPassword);
            
            if (success) {
                JSONUtil.printByJSON(resp, Result.success("密码修改成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("密码修改失败，请检查原密码是否正确"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 上传头像
     */
    @RequestMapping("/uploadAvatar.do")
    public void uploadAvatar(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            String avatarUrl = req.getParameter("avatarUrl");
            
            if (userId == null || avatarUrl == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            boolean success = userProfileService.updateAvatar(userId, avatarUrl);
            
            if (success) {
                JSONUtil.printByJSON(resp, Result.success("头像更新成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("头像更新失败"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 检查资料完整性
     */
    @RequestMapping("/checkCompleteness.do")
    public void checkProfileCompleteness(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            
            if (userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
                return;
            }
            
            Map<String, Object> completenessInfo = userProfileService.checkProfileCompleteness(userId);
            
            JSONUtil.printByJSON(resp, Result.success(completenessInfo, "检查完成"));
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 获取账户安全信息
     */
    @RequestMapping("/securityInfo.do")
    public void getSecurityInfo(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            
            if (userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
                return;
            }
            
            Map<String, Object> securityInfo = userProfileService.getSecurityInfo(userId);
            
            JSONUtil.printByJSON(resp, Result.success(securityInfo, "查询成功"));
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 验证用户身份
     */
    @RequestMapping("/verifyIdentity.do")
    public void verifyIdentity(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            String password = req.getParameter("password");
            
            if (userId == null || password == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            boolean verified = userProfileService.verifyIdentity(userId, password);
            
            if (verified) {
                JSONUtil.printByJSON(resp, Result.success("身份验证成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("身份验证失败"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 密码强度验证
     */
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 8 || password.length() > 20) {
            return false;
        }
        
        // 检查是否包含字母和数字
        boolean hasLetter = password.matches(".*[a-zA-Z].*");
        boolean hasDigit = password.matches(".*\\d.*");
        
        return hasLetter && hasDigit;
    }
}
